package net.zoneland.knowledge.service.impl.search;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.config.SearchStrategyConfig;
import net.zoneland.knowledge.constant.BizConstant;
import net.zoneland.knowledge.enums.TypeEnum;
import net.zoneland.knowledge.model.QaResponse;
import net.zoneland.knowledge.service.EsService;

/**
 * .
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryChat")
public class SearchOperationImplQueryChat extends AbstractSearchOperation {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationImplQueryChat.class);

    @Autowired
    private EsService esService;

    @Autowired
    private SearchStrategyConfig searchStrategyConfig;
    
    @Override
    public boolean needRun(final SearchDto searchDto) {
        if (!searchStrategyConfig.isChat()) {
            return false;
        }
        return !searchDto.isStopSearch() && StringUtils.isNotEmpty(searchDto.getQaQueryDto().getQueryText());
    }

    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) throws Exception {
        LOGGER.info("start queryChat {}", searchDto);
        try {
            final String answer = esService.queryChat(searchDto.getQaQueryDto()
                                                          .getQueryText());
            QaResponse qaResponse = new QaResponse();
            if (null != answer) {
                qaResponse.setData(answer.replaceAll(BizConstant.REPLACE_ROBOT_NAME, searchDto.getQaQueryDto()
                    .getRobotName()));
                qaResponse.setType(TypeEnum.TEXT.getValue());
                searchDto.setQaResponse(qaResponse);
                searchDto.setStopSearch(true);
                searchDto.setStopDeal(true);
            }
        } catch (Exception e) {
            searchDto.setErrorFlag(true);
            LOGGER.error("SearchOperationImplQueryChat error", e);
        }
    }

}
